package com.wxdc.nmgyt.nmgytwydc.utils;

import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import com.wxdc.nmgyt.nmgytwydc.app.MyApp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2018/4/3.
 */

public class FileUtil {
    //-----------------------------------------
    private File localFileFolder;//保存文件
    private File file;
    FileOutputStream fos;
    public static final String GpsDataFile = "gpsDataFile";
    public static final String MapImageFile = "mapImageFile";
    public static final String MapLayerFile = "mapLayerFile";
    public static final String ImageFile = "jczPictures";
    public static final String OpenfilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "jczApp" + File.separator + "gpsDataFile" + File.separator;
    public static final String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "jczApp" + File.separator;

    public FileUtil(String filderName) {
        localFileFolder = new File(filePath + filderName);
        if (!localFileFolder.exists()) {
            localFileFolder.mkdirs();
        }
    }

    public FileOutputStream getFileOutputstream(String fileName) {
        // 定义文件输出流
        file = new File(localFileFolder.getAbsolutePath(), fileName + "(" + currtDateTime() + ").txt");
        try {
            fos = new FileOutputStream(file, true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return fos;
    }

    public void writeFile(FileOutputStream fos, String info) {
        if (fos != null) {
            try {
                fos.write(info.getBytes());
                fos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void close(FileOutputStream fos) {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //--------------获取系统当前时间----------------------
    private String currtDateTime() {
        String dataInfo = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd  HH:mm");
        Date currtData = new Date(System.currentTimeMillis());
        dataInfo = simpleDateFormat.format(currtData);

        /*Calendar calendar=Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        int millisecond = calendar.get(Calendar.MILLISECOND);
        dataInfo=year+"年"+month+"月"+day+"日"+hour+"时"+minute+"分"+second+"秒"+millisecond+"毫秒";*/
        return dataInfo;
    }
    /*
    * 创建文件夹
    * */

    public static File createImageFolder() {
        File imageFolder = new File(filePath + MapImageFile);
        if (!imageFolder.exists()) {
            imageFolder.mkdirs();
        }
        return imageFolder;
    }

    public static File createLayerFolder() {
        File layerFolder = new File(filePath + MapLayerFile);
        if (!layerFolder.exists()) {
            layerFolder.mkdirs();
        }
        return layerFolder;
    }

    public static File createGpsDatarFolder() {
        File gpsDataFolder = new File(filePath + GpsDataFile);
        if (!gpsDataFolder.exists()) {
            gpsDataFolder.mkdirs();
        }
        return gpsDataFolder;
    }

    /*
    * 在和图片所在的文件夹的同一级目录里，新建一个名为“.nomedia”的文件夹（记住nomedia前面有一点）。
    * 建立之后看不到".nomedia"文件夹，因为在安卓手机里面前面加点的文件或者文件夹是默认隐藏的，
    * 可以通过菜单键来设置为显示隐藏文件就可以看到加了点的文件夹了。如果你要隐藏文件的话，也可以在原来的文件名称前加一个点就行了。
    * */
    public static File createPicImageFolder() {
        File getImageFolder = new File(filePath + ImageFile);
        File hideFolder = new File(filePath + ImageFile + File.separator + ".nomedia");
        if (!getImageFolder.exists()) {
            getImageFolder.mkdirs();
            hideFolder.mkdirs();
        }
        return getImageFolder;
    }

    /*
    * 保存图片到指定文件夹
    * */
    public static String copyImage(String oldImagePath, String newImageName) {
        OutputStream output = null;
        InputStream input = null;
        File oldFile = new File(oldImagePath);
        File newFile = new File(filePath + ImageFile, newImageName + oldImagePath.substring(oldImagePath.lastIndexOf(".")));
        Log.i("TAG", "copyImage: ------------------" + newImageName + oldImagePath.substring(oldImagePath.lastIndexOf(".")));
        if (newFile.exists()) {//判断有没有相同文件存在
            newFile.delete();
        }
        try {
            input = new FileInputStream(oldFile);// 打开输入流
            output = new FileOutputStream(newFile);// 打开输出流
            // 读取和写入信息
            byte[] b = new byte[1024 * 5];// 创建一个字节数组，当做缓冲区
            int len;
            while ((len = input.read(b)) != -1) {
                output.write(b, 0, len);
            }
            output.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流  先开后关  后开先关
            try {
                output.close();// 后开先关
                input.close();// 先开后关

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        //发送广播更新系统相册
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(newFile);
        intent.setData(uri);
        MyApp.getInstance().getApplicationContext().sendBroadcast(intent);
        Log.i("TAG", "copyImage:------------------ " + newFile.getAbsolutePath());
        return newFile.getAbsolutePath() + "?" + Math.random();//保证每次图片从服务器请求
    }

    /*
    * 删除本地文件夹及文件
    * */

    public static void recurDelete(File f) {
        try {
            for (File fi : f.listFiles()) {
                if (fi.isDirectory()) {
                    recurDelete(fi);
                } else {
                    fi.delete();
                }
            }
            f.delete();
        } catch (NullPointerException n) {
            System.out.println("Sorry,No such file");
        }

    }
    /*
    * 删除本地文件
    * */
    public static void deleteFile(String filePath){
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            file.delete();
        }
       sendBrodacase(file);
    }
    /*
    * 发送广播，更新系统相册
    * */
    private static void sendBrodacase(File file){
        //发送广播更新系统相册
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        MyApp.getInstance().getApplicationContext().sendBroadcast(intent);
    }
}
